<template>
  <div class="q-pa-md">
    <div class="q-gutter-y-md column" style="max-width: 300px"></div>
    

    <div class="q-pb-sm">
      日期区间: {{ selectDate }}
    </div>
    

    <q-date v-model="selectDate" range />

    <q-input standout color="orange" v-model="textName" label="发送人姓名输入">

    </q-input>

    <!-- <q-select v-model="modelroom" :options="options" label="Standard" /> -->
    <!-- <ul>
        <li v-for="item in items" :key="item.id">{{ item.name }}</li>
      </ul> -->
    <q-select filled v-model="modelroom" :options="options" option-value="roomid" option-label="roomname" label="房间选择"
      map-options />

    <q-input standout color="orange" v-model="textBody" label="模糊文字查询">

    </q-input>




    <q-form>
      <q-btn label="查询" color="primary" @click="query" />
      <q-btn label="后台更新" color="secondary" @click="onUpdate" />
      <q-btn label="跳转" color="yellow" @click="goToAbout" />
      <!-- 使用事件处理器 -->
    </q-form>

  </div>

  
 


  <div class="q-pa-md">
    <q-table class="my-sticky-column-table" flat bordered ref="mytable" title="Dialogue" :rows="orignData" :columns="columns"
      row-key="name" v-model:pagination="initialPagination" @request="onSubmit">
      <template v-slot:body-cell-filename="props">
        <q-td key="name" :props="props">
          <a target="_blank" :href="'http://172.51.3.121:8080/file/' + props.row.filename">{{ props.row.filename }}</a>
        </q-td>
      </template>
      <template v-slot:top-right>
        <q-btn color="primary" icon-right="archive" label="Export to csv" no-caps @click="exportTable" />
      </template>
    </q-table>
  </div>






</template>



<script>
// import { useQuasar } from 'quasar'
// import { onMounted } from 'vue'
import axios from 'axios'
import { ref} from 'vue'
import { exportFile, useQuasar } from 'quasar'


// import { createDOMCompilerError } from '@vue/compiler-dom';

function wrapCsvValue(val, formatFn, row) {
  let formatted = formatFn !== void 0
    ? formatFn(val, row)
    : val

  formatted = formatted === void 0 || formatted === null
    ? ''
    : String(formatted)

  formatted = formatted.split('"').join('""')
  /**
   * Excel accepts \n and \r in strings, but some other CSV parsers do not
   * Uncomment the next two lines to escape new lines
   */
  // .split('\n').join('\\n')
  // .split('\r').join('\\r')

  return `"${formatted}"`
}

const columns= [
  // {
  //   name: 'msgtime',
  //   required: true,
  //   label: 'Dessert (100g serving)',
  //   align: 'left',
  //   field: row => row.name,
  //   format: val => `${val}`,
  //   sortable: true
  // },
  // { name: 'recallflg', align: 'left', label: '回撤标记', field: 'recallflg' },
  { name: 'reffromstr', align: 'left', label: '发送人姓名', field: 'reffromstr' },
  { name: 'refroomid', align: 'left', label: '房间号', field: 'refroomid' },
  { name: 'refmsgtime', align: 'left', label: '时间', field: 'refmsgtime' },
  { name: 'msgtype', align: 'left', label: '类型', field: 'msgtype' },
  { name: 'text', align: 'left', label: '对话文字', field: 'text', style: () => ('width: 100px') },
  { name: 'filename', align: 'left', label: '图片、文件、视频路径', field: 'filename' },


];
// var data= [];

export default {
  methods: {
    goToAbout(){
      this.$router.push({ path: '/childView'});
    },
    query() {
      this.$refs.mytable.requestServerInteraction();
    },
    fetchData() {
      var self = this;
      axios.post('http://172.51.3.121:8080/readWXRoom')
        .then(function (response) {
          // handle success
          console.log(response);
          // responseMessage.value  = response.data.data.retStr;
          self.options = response.data.data;
          // this.options = response.data.data;

        })
        .catch(function (error) {
          // handle error
          console.log(error);

        })
        .then(function () {
          // always executed
          // $q.notify({
          //   color: 'green-4',
          //   textColor: 'white',
          //   icon: 'cloud_done',
          //   message: 'Submitted'
          // })

          // $q.loading.hide();
        });
    },
    
  },

  data() {
    return {

      

      items: [],
      options: [],
      initialPagination: {
        sortBy: 'desc',
        descending: false,
        page: 1,
        rowsPerPage: 10,
        // rowsNumber: xx if getting data from a server
      },

    }
  },
  

  created() {
    //页面初期化加载
    this.fetchData();

  },

  updated() {

  },

  setup() {
    let textName = ref('');
    let textBody = ref('');
    let selectDate = ref(null);
    let modelroom = ref(null);
    let orignData = ref([]);
    let initialPagination = ref({
        sortBy: 'desc',
        descending: false,
        page: 1,
        rowsPerPage: 10
        // rowsNumber: xx if getting data from a server
      });


    const $q = useQuasar()
    return {
      columns,
      textName,
      textBody,
      selectDate,
      modelroom,
      orignData,
      

      onSubmit(props) {

          // $q.loading.show({
          //   message: '鏌ヨ�㈡暟鎹�璇风◢鍚庯紒',
          //   boxClass: 'bg-grey-2 text-grey-9',
          //   spinnerColor: 'primary'
          // })

          // chatWithGPT(submitMessage.value);
          //var dateNow = new Date();
          var form3 = {
            pageSize: 10,
            pageNum: 1,
            orderBy: '',
            beginTime: '',
            endTime: '',
            textName: '',

            roomId: '',
            textBody: '',

          }
          const { page, rowsPerPage } = props?.pagination;
          form3.pageNum = page;
          form3.pageSize = rowsPerPage;
          form3.textName = textName.value;
          if (null != selectDate.value) {
            if (null ==selectDate.value.from) {
              form3.beginTime = selectDate.value;
              form3.endTime = selectDate.value;
            } else {
              form3.beginTime = selectDate.value.from;
              form3.endTime = selectDate.value.to;
            }
          }
          if (null != modelroom.value) {
            form3.roomId = modelroom.value.roomid;
          }

          if (null != textBody.value) {
            form3.textBody = textBody.value;
          }


          axios.post('http://172.51.3.121:8080/readWXRecord', form3)
            .then(function (response) {
              // handle success
              console.log(response);

              // responseMessage.value  = response.data.data.retStr;
              orignData.value = response.data.data.rows;
              initialPagination.value.page = response.data.data.pageNum;
              initialPagination.value.rowsPerPage = response.data.data.pageSize;
              initialPagination.value.rowsNumber = response.data.data.total;
            })
            .catch(function (error) {
              // handle error
              console.log(error);

            })
            .then(function () {
              // always executed
              // $q.notify({
              //   color: 'green-4',
              //   textColor: 'white',
              //   icon: 'cloud_done',
              //   message: 'Submitted'
              // })

              // $q.loading.hide();
            });
          },
      

      exportTable() {
        // naive encoding to csv format
        const content = [columns.map(col => wrapCsvValue(col.label))].concat(
          orignData.value.map(row => columns.map(col => wrapCsvValue(
            typeof col.field === 'function'
              ? col.field(row)
              : row[col.field === void 0 ? col.name : col.field],
            col.format,
            row
          )).join(','))
        ).join('\r\n')

        const status = exportFile(
          'table-export.csv',
          content,
          'text/csv'
        )

        if (status !== true) {
          $q.notify({
            message: 'Browser denied file download...',
            color: 'negative',
            icon: 'warning'
          })
        }
      },
      



      onReset() {

      },
      onUpdate() {

        $q.loading.show({
          message: '后台更新中，请稍后！',
          boxClass: 'bg-grey-2 text-grey-9',
          spinnerColor: 'primary'
        })

        //<!-- http://172.51.3.121:8099 -->
        axios.get('http://127.0.0.1:8080/updateWXRecord')
          .then(function (response) {
            // handle success
            console.log(response);

          })
          .catch(function (error) {
            // handle error
            console.log(error);
          })
          .then(function () {
            // always executed
            // $q.notify({
            //   color: 'green-4',
            //   textColor: 'white',
            //   icon: 'cloud_done',
            //   message: 'Submitted'
            // })

            $q.loading.hide();
          });
      },

      caouploaded(info) {
        var formcaouploaded = {
          errorCode: null,
          errorMsg: null,
          data: null

        }
        formcaouploaded = JSON.parse(info.xhr.response)
        console.log(formcaouploaded.errorCode)
        if ("00000" == formcaouploaded.errorCode) {
          // alert("姝ｇ‘")
        } else {
          alert("后台连接出错！")
        }


        console.log(info);
      },

    }
  }

}


</script>

<style lang="sass">
.my-sticky-column-table
  /* specifying max-width so the example can
    highlight the sticky column on any browser window */
  max-width: 1600px

  

  .q-table__top,
  .q-table__bottom,
  thead tr:first-child th
    /* bg color is important for th; just specify one */
    background-color: #00b4ff

  thead tr th
    position: sticky
    z-index: 1
  thead tr:first-child th
    top: 0

  /* this is when the loading indicator appears */
  &.q-table--loading thead tr:last-child th
    /* height of all previous header rows */
    top: 48px

  /* prevent scrolling behind sticky top row on focus */
  tbody
    /* height of all previous header rows */
    scroll-margin-top: 48px
</style>
